<template>
  <div class="register">
    <el-form
      ref="registerForm"
      :model="registerForm"
      :rules="registerRules"
      class="register-form"
    >
      <h3 class="title">注册</h3>
      <div class="row-form">
        <el-form-item prop="corporateName">
          <el-input
            v-model="registerForm.corporateName"
            type="text"
            auto-complete="off"
            placeholder="供应商单位"
          >
            <svg-icon
              slot="prefix"
              icon-class="user"
              class="el-input__icon input-icon"
            />
          </el-input>
        </el-form-item>
        <el-form-item prop="unifiedCreditCode">
          <el-input
            v-model="registerForm.unifiedCreditCode"
            type="text"
            auto-complete="off"
            placeholder="统一信用代码"
          >
            <svg-icon
              slot="prefix"
              icon-class="user"
              class="el-input__icon input-icon"
            />
          </el-input>
        </el-form-item>
        
      </div>
      <div class="row-form">
        <el-form-item prop="legalPerson">
          <el-input
            v-model="registerForm.legalPerson"
            type="text"
            auto-complete="off"
            placeholder="法人联系人"
          >
            <svg-icon
              slot="prefix"
              icon-class="user"
              class="el-input__icon input-icon"
            />
          </el-input>
        </el-form-item>
        <el-form-item prop="legalPhone">
          <el-input
            v-model="registerForm.legalPhone"
            type="text"
            auto-complete="off"
            placeholder="法人手机号"
          >
            <svg-icon
              slot="prefix"
              icon-class="user"
              class="el-input__icon input-icon"
            />
          </el-input>
        </el-form-item>
       
      </div>
      <div class="row-form">
         <el-form-item prop="handledBy">
          <el-input
            v-model="registerForm.handledBy"
            type="text"
            auto-complete="off"
            placeholder="经办人"
          >
            <svg-icon
              slot="prefix"
              icon-class="user"
              class="el-input__icon input-icon"
            />
          </el-input>
        </el-form-item>
        <el-form-item prop="handledByPhone">
          <el-input
            v-model="registerForm.handledByPhone"
            type="text"
            auto-complete="off"
            placeholder="经办人手机号(登录账号)"
          >
            <svg-icon
              slot="prefix"
              icon-class="user"
              class="el-input__icon input-icon"
            />
          </el-input>
        </el-form-item>
        
      </div>
      <div class="row-form">
        <el-form-item prop="email">
          <el-input
            v-model="registerForm.email"
            type="text"
            auto-complete="off"
            placeholder="邮箱"
          >
            <svg-icon
              slot="prefix"
              icon-class="user"
              class="el-input__icon input-icon"
            />
          </el-input>
        </el-form-item>
        <el-form-item prop="address">
          <el-input
            v-model="registerForm.address"
            type="text"
            auto-complete="off"
            placeholder="地址"
          >
            <svg-icon
              slot="prefix"
              icon-class="user"
              class="el-input__icon input-icon"
            />
          </el-input>
        </el-form-item>
        
      </div>
      
      <div class="row-form">
        <el-form-item prop="file">
        <el-upload
          action="#"
          :show-file-list="false"
          :on-change="beforeUpload"
          :auto-upload="false"
        >
          <img
            v-if="file.imageUrl"
            :src="file.imageUrl"
            style="width: 150px; height: 200px"
          />
          <el-input
            v-else
            readonly
            placeholder="点击上传营业执照"
            v-model="file.name"
          >
          <svg-icon
              slot="prefix"
              icon-class="user"
              class="el-input__icon input-icon"
            /></el-input>
        </el-upload>
      </el-form-item>
      <el-form-item prop="typeIds">
        <el-cascader v-model="registerForm.typeIds" :props="cascaderProps" collapse-tags placeholder="请选择公司类别"> </el-cascader>
      </el-form-item>
      </div>
      <div class="row-form">
        <el-form-item prop="password">
          <el-input
            v-model="registerForm.password"
            type="password"
            auto-complete="new-password"
            placeholder="密码"
            @keyup.enter.native="handleRegister"
          >
            <svg-icon
              slot="prefix"
              icon-class="password"
              class="el-input__icon input-icon"
            />
          </el-input>
        </el-form-item>
        <el-form-item prop="confirmPassword">
          <el-input
            v-model="registerForm.confirmPassword"
            type="password"
            auto-complete="new-password"
            placeholder="确认密码"
            @keyup.enter.native="handleRegister"
          >
            <svg-icon
              slot="prefix"
              icon-class="password"
              class="el-input__icon input-icon"
            />
          </el-input>
        </el-form-item>
      </div>
      <el-form-item style="width: 100%">
        <el-button
          :loading="loading"
          size="medium"
          type="primary"
          style="width: 100%"
          @click.native.prevent="handleRegister"
        >
          <span v-if="!loading">注 册</span>
          <span v-else>注 册 中...</span>
        </el-button>
        <div style="float: right">
          <router-link class="link-type" :to="'/login'"
            >使用已有账户登录</router-link
          >
        </div>
      </el-form-item>
    </el-form>
    <!--  底部  -->
    <div class="el-register-footer">
      <span>Copyright © 2018-2023 比特元 All Rights Reserved.</span>
    </div>
  </div>
</template>

<script>
import { getCodeImg, register } from "@/api/login";
import { listMaterial, listType } from "@/api/purchase/api";
export default {
  computed:{
    cascaderProps(){
        return{
          lazy:true,
          multiple: true,
          lazyLoad:this.lazyLoad,
          emitPath: false
        }
      },
  },
  name: "Register",
  // dicts: ['sys_company_category'],
  data() {
    const validateEmail = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请正确填写邮箱"));
      } else {
        var reg =
          /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
        if (!reg.test(value)) {
          callback(new Error("请输入有效的邮箱"));
          return;
        }
        callback();
      }
    };
    const validatePhone = (rule, value, callback) => {
      const regExp =
        /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/;
      if (!regExp.test(value)) {
        callback(new Error("请输入正确的手机号"));
      } else {
        callback();
      }
    };
    const equalToPassword = (rule, value, callback) => {
      if (this.registerForm.password !== value) {
        callback(new Error("两次输入的密码不一致"));
      } else {
        callback();
      }
    };
    return {
      codeUrl: "",
      registerForm: {
        corporateName: "",
        legalPerson: "",
        legalPhone: "",
        handledBy: "",
        handledByPhone: "",
        email: "",
        address: "",
        typeIds: [],
        password: "",
        confirmPassword: "",
        unifiedCreditCode: "",
      },
      registerRules: {
        corporateName: [
          { required: true, trigger: "blur", message: "请输入供应商单位" },
          {
            max: 30,
            message: "供应商单位名称不超过30个字符",
            trigger: "blur",
          },
        ],
        legalPerson: [
          { required: true, trigger: "blur", message: "请输入法人联系人" },
        ],
        legalPhone: [
          { required: true, validator: validatePhone, trigger: "blur" },
          { required: true, trigger: "blur", message: "请输入法人手机号" },
        ],
        handledBy: [
          { required: true, trigger: "blur", message: "请输入经办人" },
          {
            max: 10,
            message: "经办人名称不超过10个字符",
            trigger: "blur",
          },
        ],
        handledByPhone: [
          { required: true, validator: validatePhone, trigger: "blur" },
          { required: true, trigger: "blur", message: "请输入经办人手机号" },
        ],
        email: [
          { required: true, trigger: "blur", message: "请输入邮箱" },
          { required: true, validator: validateEmail, trigger: "blur" },
        ],
        address: [{ required: true, trigger: "blur", message: "请输入地址" }],
        typeIds: [{ required: true, trigger: "change", message: "请选择公司类型" }],
        unifiedCreditCode: [
          { required: true, trigger: "blur", message: "请输入统一信用代码" },
        ],
        password: [
          { required: true, trigger: "blur", message: "请输入您的密码" },
          {
            min: 5,
            max: 20,
            message: "用户密码长度必须介于 5 和 20 之间",
            trigger: "blur",
          },
        ],
        confirmPassword: [
          { required: true, trigger: "blur", message: "请再次输入您的密码" },
          { required: true, validator: equalToPassword, trigger: "blur" },
        ],
        // code: [{ required: true, trigger: "change", message: "请输入验证码" }],
      },
      loading: false,
      captchaEnabled: true,
      fileList: [],
      file: {
        imageUrl: "",
      },
    };
  },
  created() {
    // this.getCode();
  },
  methods: {
    //懒加载
    async lazyLoad(node, resolve){
      let level = node.level
      let result
      switch (level) {
        case 0:
          let initRes = await listMaterial()
          result = initRes.rows
          result.forEach((item) =>{
            item.value = item.materialTypeId
            item.label = item.materialTypeName
          })
          break;
        case 1:
          let firstParams = {
            typeId:node.data.value
          }
        let firstRes = await listType(firstParams)
          result = firstRes.data
          result.forEach((item) =>{
            item.value = item.materialId
            item.label = item.typeName
            item.leaf = level >= 1
          })
          break;
      
        default:
          break;
      }
      resolve(result)
    },
    // 上传预处理
    beforeUpload(file) {
      if (file.raw.type.indexOf("image/") == -1) {
        this.$modal.msgError(
          "文件格式错误，请上传图片类型,如：JPG，PNG后缀的文件。"
        );
      } else {
      console.log('file',file)
        this.registerForm.file = file.raw;
        this.fileList.push(file.raw);
        const reader = new FileReader();
        reader.readAsDataURL(file.raw);
        reader.onload = () => {
          this.file.imageUrl = reader.result;
        };
      }
    },
    // getCode() {
    //   getCodeImg().then((res) => {
    //     this.captchaEnabled =
    //       res.captchaEnabled === undefined ? true : res.captchaEnabled;
    //     if (this.captchaEnabled) {
    //       this.codeUrl = "data:image/gif;base64," + res.img;
    //       this.registerForm.uuid = res.uuid;
    //     }
    //   });
    // },
    handleRegister() {
      this.$refs.registerForm.validate((valid) => {
        if (valid && this.file.imageUrl) {
          this.loading = true;
          let formData = new FormData();
          formData.append("file", this.registerForm.file);
          formData.append("corporateName", this.registerForm.corporateName);
          formData.append("legalPerson", this.registerForm.legalPerson);
          formData.append("legalPhone", this.registerForm.legalPhone);
          formData.append("handledBy", this.registerForm.handledBy);
          formData.append("handledByPhone", this.registerForm.handledByPhone);
          formData.append("email", this.registerForm.email);
          formData.append("address", this.registerForm.address);
          formData.append("typeIds", this.registerForm.typeIds);
          formData.append("password", this.registerForm.password);
          formData.append(
            "unifiedCreditCode",
            this.registerForm.unifiedCreditCode
          );
          register(formData)
            .then((res) => {
              const username = this.registerForm.handledByPhone;
              this.$alert(
                "<font color='red'>恭喜你，您的账号 " +
                  username +
                  " 注册成功！</font>",
                "系统提示",
                {
                  dangerouslyUseHTMLString: true,
                  type: "success",
                }
              )
                .then(() => {
                  this.$router.push("/login");
                })
                .catch(() => {});
            })
            .catch(() => {
              this.loading = false;
              this.fileList = [];
              // if (this.captchaEnabled) {
              //   this.getCode();
              // }
            });
        }else{
          this.$modal.msgError(
          "请确认是否正确填写了注册信息并上传了营业执照"
        );
        }
      });
    },
  },
};
</script>

<style rel="stylesheet/scss" lang="scss">
.register {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  background-image: url("../assets/images/login-background.jpg");
  background-size: cover;
}
.title {
  margin: 0px auto 30px auto;
  text-align: center;
  color: #707070;
}

.register-form {
  border-radius: 6px;
  background: #ffffff;
  width: 530px;
  padding: 25px 25px 5px 25px;
  .row-form {
    display: flex;
    justify-content: space-between;
  }
  .el-input {
    height: 38px;
    width: 230px;
    input {
      height: 38px;
    }
  }
  .input-icon {
    height: 39px;
    width: 14px;
    margin-left: 2px;
  }
}
.register-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}
.register-code {
  margin-left: 20px;
  height: 38px;
  img {
    cursor: pointer;
    vertical-align: middle;
  }
}
.el-register-footer {
  height: 40px;
  line-height: 40px;
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
  color: #fff;
  font-family: Arial;
  font-size: 12px;
  letter-spacing: 1px;
}
.register-code-img {
  height: 38px;
}
</style>
